import { Injectable, UnauthorizedException } from "@nestjs/common";
import { ExtractJwt, Strategy, VerifiedCallback } from 'passport-jwt';
import { PassportStrategy } from "@nestjs/passport";
import { AuthService } from "./auth.service";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super({
      // 这里没有intellisense可以用，下面这一段是说
      // 要从header取得bearer token
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      // ignoreExpiration: false,
      // 这里的key就是要跟create token时的key一样
      secretOrKey: '345edrfertertert',
      // issuer: 'https://www.geekjc.com',
    })
  }

  // Passport会自动verify jwt，如果key不正确，或是相关信息
  // 不正确，如issuer
  async validate(payload, done: VerifiedCallback){
    // console.log('234234');
    // payload：jwt-passport认证jwt通过后解码的结果
    const user = await this.authService.validateToken(payload);
    if (!user) throw new UnauthorizedException();
    return user;
  }
}